#include <func.h>
#include "head.h"
// int upload(char* argv, int sockFd){
//     //puts file
//     char arr[100] = "";
//     strcpy(arr, argv);
//     char* command = strtok(arr, " ");
//     char* fileName = strtok(NULL, " ");
//     char realName[100] = {0};
//     strncpy(realName, fileName, strlen(fileName) - 1);
//     int fd = open(realName, O_RDWR);
//     ERROR_CHECK(fd, -1, "open");
//     struct stat statbuf;
//     fstat(fd, &statbuf);
//     train_t t;
//     t.dataLength = sizeof(statbuf.st_size);
//     memcpy(t.buf, &statbuf.st_size, sizeof(statbuf.st_size));
//     send(sockFd, &t, sizeof(t.dataLength) + t.dataLength, MSG_NOSIGNAL);//发送文件长度   
//     char *p = (char *)mmap(NULL, statbuf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
//     send(sockFd, p, statbuf.st_size, MSG_NOSIGNAL);  
//     munmap(p, statbuf.st_size);
//     close(fd);
// }

int upload(char *argv, int sockFd){
    //puts file1
    char arr[100] = "";
    strcpy(arr, argv);
    char* command = strtok(arr, " ");
    char* fileName = strtok(NULL, " ");
    //char realName[100] = {0};
    //strncpy(realName, fileName, strlen(fileName) - 1);
    int fd = open(fileName, O_RDWR);
    ERROR_CHECK(fd, -1, "open");

    struct stat statbuf;
    fstat(fd, &statbuf);
    //先获取md5码
    unsigned char Md5[16];
    char md5[100] = {0};
    char *q = md5;
    char *p = (char *)mmap(NULL, statbuf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    MD5((unsigned char *)p, statbuf.st_size, Md5);
    for(int i = 0; i < 16; i++){
        sprintf(q, "%02x", Md5[i]);
        q += 2;
    }
    train_t t;
    t.dataLength = strlen(md5);
    strcpy(t.buf, md5);
    send(sockFd, &t, sizeof(t.dataLength) + t.dataLength, MSG_NOSIGNAL);

    //md5码发送给服务端，服务端负责在数据库内查找是否已存在该文件
    
    //收到服务器发来的判断文件是否存在的信号
    char recvSig;
    recv(sockFd, &recvSig, 1, MSG_WAITALL);
    if(recvSig == '1'){//文件不存在， 进行上传工作
        bzero(&t, sizeof(t));
        t.dataLength = sizeof(statbuf.st_size);
        memcpy(t.buf, &statbuf.st_size, sizeof(statbuf.st_size));
        send(sockFd, &t, sizeof(t.dataLength) + t.dataLength, MSG_NOSIGNAL);//发送文件长度   
        send(sockFd, p, statbuf.st_size, MSG_NOSIGNAL);
        recv(sockFd, &recvSig, 1, 0);
        if(recvSig == '1'){
            puts("Upload Success!!");
        }
    }
    else if(recvSig == '0'){ //文件已存在，完成秒传，跳出函数
        puts("Upload Success!!");       
    }
    return 0;
}